package com.x.share.api.controller;

import java.util.Map;

import javax.annotation.Resource;

import com.x.share.mid.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.x.share.mid.exception.HelperException;
import com.x.share.mid.model.AToken;
import com.x.share.mid.model.ATokenOut;
import com.x.share.mid.prop.ShareProperties;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api("api调用者认证")
@RestController
@RequestMapping("/api/")
public class ApiAuthController extends BaseController {

	@Resource
	ShareProperties shareProps;

	@ApiOperation(value = "api接口认证", notes = "调用认证接口后，务必将appId及accessToken放到http的请求头里(appId: appId, atk: accessToken)，以保证后续的接口正常访问", response = ATokenOut.class)
	@RequestMapping(value = "auth", method = { RequestMethod.POST })
	public @ResponseBody Map<String, Object> auth(
			@ApiParam(value = "app应用id, 10000：前端，10001：商家端，10002：平台后台", allowableValues = "10000, 10001, 10002") @RequestParam(value = "appId", required = true) String appId,
			@ApiParam(value = "app密钥", example = "api管理员发给您的密钥，不要告诉别人!") @RequestParam(value = "secret", required = true) String secret) throws HelperException {
		String secret2 = AToken.APPLICATION.get(appId);
		if (StringUtils.isNotBlank(secret2) && secret2.equals(secret)) {
			AToken atk = new AToken();
			atk.setAppId(appId);
			atk.setEnv(shareProps.getEnv());
			atk.setTimestamp(System.currentTimeMillis());
			String token = CodecUtils.encrypt(JSON.toJSONString(atk), shareProps.getAeskey());
			ATokenOut out = new ATokenOut();
			out.setAccessToken(token);
			out.setTimestamp(atk.getTimestamp());
			return success(out);
		} else {
			return fail("appId或密钥无效！");
		}
	}

}
